//---------------------------------------------------------------------------
// Thread Class
// Re-writer : Woo-Hyun Kim
// Email : woorung@icu.ac.kr
// Date : Jul. 7, 2006
//
// Note. this class is referred in http://joinc.co.kr/modules/moniwiki/wiki.php/Site/Thread/Advanced/ThreadClass
//---------------------------------------------------------------------------
#ifndef CThreadH
#define CThreadH

#include <iostream>
#include <iterator>
#include <vector>
#include <list>
#include <algorithm>
#include <fstream>
#include <string>

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <stdexcept>
#include <sys/types.h>
#include <sys/time.h>
#include <errno.h>
#include <sys/wait.h>
#include <signal.h>

using namespace std;
//---------------------------------------------------------------------------
class CThread {
private :
	int _state;
	bool _joinning;
	bool _isInterrupted;
	pthread_mutex_t _mutex;
	pthread_cond_t _cond;
	static pthread_attr_t _attr;
	static long _id;
	string _name;

	static void* threadHandler(void* arg);
	static void interruptHandler(int sigInt);
	void init(const string& name);

	// it must be overridden
	virtual void run() = 0;

protected :
	pthread_t _thread;

public :
	CThread();
	CThread(const string& name);

	virtual ~CThread();
	void start();
	void sleep(time_t sec);
	void join();
	void join(unsigned long sec);
	void interrupt();
	bool isInterrupted();
	bool isAlive();
	char *getName();
	void setName(char *name);
};
//---------------------------------------------------------------------------
class InterruptedException : public exception {
private:
	string _message;

public:
	explicit InterruptedException(const string&  message) : _message(message) {}
	virtual ~InterruptedException() throw() {}
	virtual const char* what() const throw() {
		return _message.c_str();
	}
};
//---------------------------------------------------------------------------
class IllegalThreadStateException : public exception {
private:
	string _message;

public:
	explicit IllegalThreadStateException(const string&  message) : _message(message) {}
	virtual ~IllegalThreadStateException() throw() {}
	virtual const char* what() const throw() {
		return _message.c_str();
	}
};
//---------------------------------------------------------------------------
#endif
